//
//  TJTabBar.swift
//  weibo
//
//  Created by 简祖明 on 16/7/27.
//  Copyright © 2016年 汤娟. All rights reserved.
//

import UIKit

//自定义的tabBar
class TJTabBar: UITabBar {

    //定义一个闭包
    var closure : (() -> ())?
    
    //布局
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加子控件
        setupUI()
    }
    
    //storyBoard加载的时候使用这个方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //添加按钮
        addSubview(composeBtn)
    }
    
    //重新布局子控件
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        //设置item的宽高
        let width = bounds.width/5
        let height = bounds.height
        //默认的索引
        var index = 0
        
        for subview in subviews {
            //判断传进来的subview是不是tabbarButton
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //设置子控件的frame
            subview.frame = CGRectMake(width * CGFloat(index) ,subview.frame.origin.y,width,height)
            
                index++
                //当等于中间特殊按钮的时候跳过
                if index==2 {index++}
            }
        }
        
        //设置按钮的frame
        composeBtn.frame = CGRectMake(2 * width, bounds.origin.y, width, height)
    }
    
    //懒加载（中间的按钮）
    lazy var composeBtn : UIButton = {
        let button = UIButton()
        
        //设置按钮属性
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        
        //添加按钮的点击事件
        button.addTarget(self, action: "btnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.sizeToFit()
        
        return button
    }()
    
    //tabBar中间按钮的点击事件
    func btnClick() {
        print("点击")
        //调用闭包
        closure?()
    }
    
}







